package com.zzyl.framework.interceptor;

import cn.hutool.http.HttpStatus;
import com.zzyl.common.utils.UserIdThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
@Slf4j
public class AppInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenService tokenService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       log.info("拦截器开始拦截");
        String token = request.getHeader("Authorization");
        log.info("获取到的token{}", token);
        if(!StringUtils.hasText(token)){
             response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
             return false;
        }
        //解析token
        try {
            Claims claims = tokenService.parseToken(token);
            Object userId = claims.get("id");
            log.info("用户id:{}",userId);
            UserIdThreadLocal.set((Integer)userId);
        } catch (Exception e) {
           log.error("解析token异常:{}",e.getMessage());
           response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
           return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }
}
